<template>
  <div class="vue-box" style="background-color: rgb(242,243,246);">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-light">
              <div id="totalOrderEcharts" :style="{ width: '100%', height: '500px' }"></div>
            </div>
          </el-col>
        </el-row>

      </el-col>

      <el-col :span="12">
        <div class="grid-content bg-purple-light">
          <div id="transparentOrder" :style="{ width: '100%', height: '500px' }"></div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">


      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>作业信息</span>
        </div>
        <el-col :span="12">
          <div class="grid-content bg-purple-light">
            <div :style="{ width: '100%', height: '300px' }">

            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light">
            <div id="pieChart" :style="{ width: '100%', height: '300px' }"></div>
          </div>
        </el-col>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import rpc from '@/utils/rpc.json'
import * as echarts5 from 'echarts5';

export default {
  name: 'Home',
  data() {
    return {
      chinaMap: "",//中国地图
      chinaoption: {},
      msg: 'Welcome to kala cloud.com',
      data: [],//地图数据
      startTimeMonth: [],// 近7天日期
      everydayOrderNumber: [],//每天订单数量
      lastDaysNumber: [],  //近7天数量
      lastDaysTimeMonth: [], //查询到有数据的近七天日期
      option: {},
      activeName: "first",
      tabPosition: "left",

    }
  },
  created() {
    this.queryCartographicInformation();
    this.queryEverydayOrderNumber();
  },
  computed: {
    red() {
      return red
    }
  },
  mounted() {
    setTimeout(() => {
      this.$nextTick(function () {
        this.chinaConfigure();
      });
    }, 0)
    this.drawPieChart()
  },
  methods: {

    //饼图
    drawPieChart() {
      let myPieChart = echarts5.init(document.getElementById('pieChart'));
      myPieChart.setOption(
        {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            top: '5%',
            left: 'center'
          },
          series: [
            {
              name: '详细信息',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },

              labelLine: {
                show: false
              },
              data: [
                {value: 1048, name: '取件任务待派遣'},
                {value: 30, name: '取件任务已派遣'},
                {value: 28, name: '取件任务已完成'},

              ]
            }
          ]
        });
    },

    //查询每日订单数量
    async queryEverydayOrderNumber() {
      this.getStartDateOfMonth();
      let result = await axios.get("/api/pd-aggregationcjj/pd-order/queryEverydayOrderNumber",
        {params: {startDate: this.startTimeMonth[0], endDate: this.startTimeMonth[6]}})
      let array = [];
      this.startTimeMonth.forEach((n, i) => {
        array.push({number: 0, date1: n})
      })
      let json = result.data.data.concat(array); //两个数组对象合并
      let newJson = []; //盛放去重后数据的新数组
      for (const item1 of json) {  //循环json数组对象的内容
        let flag = true;  //建立标记，判断数据是否重复，true为不重复
        for (const item2 of newJson) {  //循环新数组的内容
          if (item1.date1 == item2.date1) { //让json数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
            flag = false;
          }
        }
        if (flag) { //判断是否重复
          newJson.push(item1); //不重复的放入新数组。  新数组的内容会继续进行上边的循环。
        }
      }
      newJson.forEach((n, i) => {
        this.lastDaysNumber[i] = n.number;
        this.lastDaysTimeMonth[i] = n.date1;
      })
      this.drawOrderTotal();


    },

    // 查询每个省份收货数量以及寄货数量
    async queryCartographicInformation() {
      let result = await axios.post("/api/pd-aggregationcjj/pd-area/queryCartographicInformation");
      this.data = result.data.data;
    },

    // 画柱状图
    drawOrderTotal() {
      // 基于刚刚准备好的 DOM 容器，初始化 EChart 实例
      let myChart = echarts5.init(document.getElementById('totalOrderEcharts'))
      // 绘制图表
      myChart.setOption({
        title: {text: '订单总量'},
        tooltip: {},
        xAxis: {
          data: this.lastDaysTimeMonth
        },
        yAxis: {},
        series: [{
          name: '数量',
          type: 'bar',
          data: this.lastDaysNumber,
          barWidth: 12,
          itemStyle: {
            borderRadius: [10, 10, 10, 10],
            color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: 'rgba(227,130,130,0.6)'},
              {offset: 1, color: 'rgba(220,41,41,0.6)'}
            ]),
          }
        }]
      });
    },


    // 中国地图配置代码
    async chinaConfigure() {
      this.chinaMap = echarts5.init(document.getElementById('transparentOrder'));

      echarts5.registerMap('china', rpc);
      var result = await axios.post("/api/pd-aggregationcjj/pd-area/queryCartographicInformation");
      var data = result.data.data;

      window.onresize = this.chinaMap.resize //实现地图自适应

      var geoCoordMap = {
        "台湾省": [121.509062, 25.044332],
        "河北省": [114.502461, 38.045474],
        "山西省": [112.549248, 37.857014],
        "内蒙古自治区":[111.670801, 40.818311],
        "辽宁省": [123.429096, 41.796767],
        "吉林省": [125.3245, 43.886841],
        "黑龙江省":[126.642464, 45.756967],
        "江苏省": [118.767413, 32.041544],
        "浙江省": [120.153576, 30.287459],
        "安徽省": [117.283042, 31.86119],
        "福建省": [119.306239, 26.075302],
        "江西省": [115.892151, 28.676493],
        "山东省": [117.000923, 36.675807],
        "河南省": [113.665412, 34.757975],
        "湖北省": [114.298572, 30.584355],
        "湖南省": [112.982279, 28.19409],
        "广东省": [113.280637, 23.125178],
        "广西壮族自治区": [108.320004, 22.82402],
        "海南省": [110.33119, 20.031971],
        "四川省": [104.065735, 30.659462],
        "贵州省": [106.713478, 26.578343],
        "云南省": [102.712251, 25.040609],
        "西藏自治区": [91.132212, 29.660361],
        "陕西省": [108.948024, 34.263161],
        "甘肃省": [103.823557, 36.058039],
        "青海省": [101.778916, 36.623178],
        "宁夏回族自治区": [106.278179, 38.46637],
        "新疆维吾尔自治区": [87.617733, 43.792818],
        "北京市": [116.405285, 39.904989],
        "天津市": [117.190182, 39.125596],
        "上海": [121.472644, 31.231706],
        "重庆": [106.504962, 29.533155],
        "香港特别行政区": [114.173355, 22.320048],
        "澳门特别行政区": [113.54909, 22.198951]
      }


      //给每个地区赋值
      var convertData = function (data) {

        // console.log(this.data)
        //定义一个数组
        var res = [];
        //循环遍历每个区域值
        for (var i = 0; i < data.length; i++) {
          //获取坐标
          var geoCoord = geoCoordMap[data[i].name];
          //判断是否有坐标
          if (geoCoord) {
            //往数组里设置值
            res.push({
              name: data[i].name,
              value: geoCoord.concat(i + 1),
              NDTZJH: data[i].receiverCount,//收货数量
              GSZE: data[i].senderCount,//寄货数量
              // count: data[i].count,//项目数量
            });
          }
        }
        return res;
      };
      this.chinaMap.setOption({
        backgroundColor: 'transparent',
        geo: {
          map: 'china',
          roam: false,
          zoom: 1.2,


          label: {
            normal: {
              // show: true, // 是否显示对应地名
              textStyle: {
                color: '#fff'
              }
            },
            emphasis: { // 对应的鼠标悬浮效果
              show: true,
              textStyle: {
                color: '#fff'
              }
            }
          },
          itemStyle: {
            normal: {
              areaColor: "#FC8E88FF",//地图颜色rgba(11, 50, 119, .5)
              borderWidth: 1,//设置外层边框
              borderColor: "rgba(65,154,225, 1)",//地图外边框颜色rgba(43, 196, 243, 1)
              label: {
                show: true,//是否显示标签
                textStyle: {
                  color: "rgba(255,255,255,.5)"//地图文字的颜色
                }
              }
            },
            emphasis: { // 区域强调
              areaColor: '#01215c',
            }
          },
          regions: [ // 地区
            {
              name: "南海诸岛",
              itemStyle: {
                // 隐藏地图南海诸岛
                normal: {
                  opacity: 0, // 为 0 时不绘制该图形
                }
              },
              label: {
                show: false // 隐藏文字
              }
            }
          ],
        },
        tooltip: {
          trigger: 'item',
          show: true,
          backgroundColor: "white",

          formatter: function (params) {
            if (params.data) {
              var htmlStr = '';
              htmlStr += '<div class="bgboder">';
              htmlStr += '<div id="city">' + params.name + '</div><div id="trans">收货数量：' + params.data.NDTZJH + '<span>件</span>' + '</div><div id="trans">寄货数量：' + params.data.GSZE + '<span>件</span>';
              htmlStr += '</div>';
              return htmlStr;
            } else {
            }
          },
          textStyle: {
            width: 300,
            height: 300,
          }
        },
        visualMap: {
          type: 'piecewise',
          inRange: {
            color: ['#02F6F9', '#02F6F9', '#02F6F9']
          },
          pieces: [
            {min: 0, max: 60, color: 'rgba(255,0,0,0.5)'}, //把地图小点设置成透明颜色transparent
            {
              min: 100,
              max: 10000,
              color: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.5,
                colorStops: [
                  {offset: 0, color: 'rgba(11,28,92,0)'},
                  {offset: 0.8, color: 'rgba(10,94,137, 0.5)'},
                  {offset: 1, color: 'rgba(2, 246, 249, 1)'}
                ],
                globalCoord: false // 缺省为 false
              }
            }
          ],
          show: false,
          textStyle: {
            color: '#ffffff',
            fontSize: 16
          }
        },
        series: [
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            data: convertData(data),
            symbolSize: [20, 30],
            symbol: 'image://' + require('@/icons/svg/img.png'),
          },
        ]
      });
      window.onresize = () => {
        this.chinaMap.resize()
      }
      window.addEventListener('resize', () => {
        this.chinaMap.resize()
      })
    },


    //获取前7天日期
    getStartDateOfMonth() {

      // 创建一个空数组来存储日期
      let dates = [];

      // 获取当前日期
      let now = new Date();

      // 循环获取最近 7 天的日期
      for (let i = 0; i < 7; i++) {
        // 获取当前日期的时间戳
        let timestamp = now.getTime();

        // 计算 i 天前的时间戳
        let dayTimestamp = 24 * 60 * 60 * 1000; // 一天的毫秒数
        let iDayAgoTimestamp = timestamp - i * dayTimestamp;

        // 转换为日期对象
        let date = new Date(iDayAgoTimestamp);

        // 格式化日期为 "yyyy-MM-dd" 的字符串并存入数组
        let year = date.getFullYear();
        let month = ("0" + (date.getMonth() + 1)).slice(-2);
        let day = ("0" + date.getDate()).slice(-2);
        dates.push(year + "-" + month + "-" + day);
      }
      this.startTimeMonth = dates.reverse();
    }

  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-light {
  background: rgb(254, 254, 254);
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  padding: 20px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
